// 提供todos相关的action
import axios from 'axios'

// 获取任务列表 异步
export const getList = () => {
  return async (dispatch) => {
    const res = await axios.get('http://localhost:8888/toods')
    dispatch({
      type: 'GET_LIST',
      payload: res.data,
    })
  }
}

// 添加任务
export const addTodo = (name) => {
  return async (dispatch) => {
    const res = await axios.post('http://localhost:8888/toods', {
      name,
      done: false,
    })
    dispatch({
      type: 'ADD_TODO',
      payload: res.data,
    })
  }
}

// 删除任务
export const delTodo = (id) => {
  return async (dispatch) => {
    await axios.delete('http://localhost:8888/toods/' + id)
    dispatch(getList())
  }
}

// 修改任务状态
export const updataTodo = (id, done) => {
  return async (dispatch) => {
    await axios.patch(`http://localhost:8888/toods/${id}`, { done })
    dispatch(getList())
  }
}

// 双击修改任务
export const updateText = ({ id, name }) => {
  return async (dispatch) => {
    await axios.patch(`http://localhost:8888/toods/${id}`, { name })
    dispatch(getList())
  }
}

// 删除全部完成任务
export const clearAll = (list) => {
  return (dispatch) => {
    const clearAll = async (id) => {
      await axios.delete(`http://localhost:8888/toods/${id}`)
    }
    list.forEach((item) => {
      if (item.done) {
        clearAll(item.id)
      }
    })
    dispatch(getList())
  }
}

// 复选框全选
export const checkoutAll = (e, list) => {
  return (dispatch) => {
    const checked = e.target.checked
    list.forEach(async (item) => {
      item.done = checked
      await axios.patch(`http://localhost:8888/toods/${item.id}`, {
        done: checked,
      })
    })
    dispatch({
      type: 'ALL_CHECKED',
      payload: checked,
    })
  }
}
